package salesforce;

import java.util.*;

public class NestedIterator2 implements Iterator<Integer> {
    private Deque<NestedInteger> stack = new LinkedList<>();

    public NestedIterator2(List<NestedInteger> nestedList) {
        prepareStack(nestedList);
    }

    private void prepareStack(List<NestedInteger> nestedList) {
        for (int i = nestedList.size() - 1; i >= 0; i--) {
            stack.push(nestedList.get(i));
        }
    }

    @Override
    public Integer next() {
        return stack.pop().getInteger();
    }

    @Override
    public boolean hasNext() {
        while (!stack.isEmpty() && !stack.peek().isInteger()) {
            prepareStack(stack.pop().getList());
        }
        return !stack.isEmpty();
    }
}
